using System;
using System.IO;
using UnityEngine;
using LS.Digitize;

namespace LS.Digitize
{
    public sealed class BoundsSerializer: CompoundSerializer<Bounds>
    {
        public BoundsSerializer() : base(typeof(Bounds),typeof(Vector3))
        {
            
        }
        
        public override void WriteData(IWriter writer, Bounds obj)
        {
            ISerializer subSerializer = SubSerializer;
            using (writer.WriteObjectScope())
            {
                if (subSerializer is CompoundSerializer<Vector3> cs)
                {
                    using (writer.WritePropertyScope("center"))
                    {
                        cs.WriteData(writer,obj.center);
                    }
                    using (writer.WritePropertyScope("size"))
                    {
                        cs.WriteData(writer,obj.size);
                    }
                }
                else
                {
                    using (writer.WritePropertyScope("center"))
                    {
                        subSerializer.Write(writer,obj.center);
                    }
                    using (writer.WritePropertyScope("size"))
                    {
                        subSerializer.Write(writer,obj.size);
                    }
                }
            }
        }

        public override Bounds ReadData(IReader reader)
        {
            ISerializer subSerializer = SubSerializer;
            Bounds target = default;
            using (var objScope = reader.ReadObjectScope())
            {
                string propertyName = null;
                if (subSerializer is CompoundSerializer<Vector3> ps)
                {
                    propertyName = reader.ReadPropertyName();
                    Vector3 center = ps.ReadData(reader);
                    propertyName = reader.ReadPropertyName();
                    Vector3 size = ps.ReadData(reader);
                    target = new Bounds(center, size);
                }
                else
                {
                    propertyName = reader.ReadPropertyName();
                    Vector3 center = (Vector3)subSerializer.Read(reader);
                    propertyName = reader.ReadPropertyName();
                    Vector3 size = (Vector3)subSerializer.Read(reader);
                    target = new Bounds(center, size);
                }
            }

            return target;
        }
        
        public override void ReadInto(IReader reader, ref Bounds obj)
        {
            obj = ReadData(reader);
        }
    }
}